# 数据库工具类
from contextlib import nullcontext
from platform import python_branch
import peewee
# 异步
import peewee_async
# 时间类型
import datetime

# 导入序列化工具
from playhouse.shortcuts import model_to_dict

# 连接mongo数据库
import pymongo

# python的时区库
import pytz

# 设置时区
tzinfo = pytz.timezone('Asia/Shanghai')


# 连接mongo的数据库 类

class MyMongo:

    def __init__(self, tablename='code'):
        # 数据库连接
        self.client = pymongo.MongoClient(host='localhost', port=27017, tz_aware=True, tzinfo=tzinfo)

        # 声明数据库
        self.db = self.client.mytornado
        if tablename == 'code':
            self.table = self.db.code

        if tablename == 'user':
            self.table = self.db.user

        if tablename == 'img':
            self.table = self.db.img

    # 删除数据
    def remove(self, data):
        return self.table.delete_one(data)

    # 插入数据
    def insert(self, data):

        return self.table.insert_one(data)

    # 查询单个数据
    def find_one(self, data):

        res = self.table.find_one(data)

        return res

    # 查询多个数据
    def find(self, data):

        res = self.table.find(data)

        return res

    # 修改数据
    def update(self, find, field, data):
        # 先查询
        mydata = self.table.find_one(find)
        # 指定字段
        mydata[field] = data
        # 修改
        res = self.table.update_one(find, {'$set': mydata})
        return res


mymongo = MyMongo('code')

# 删除
mymongo.remove({'name': 1})


# 修改数据
# mymongo.update({'sid':5},'sid',3)

# 查询多个
# res = mymongo.find({})
# for i in res:
#     print(i['sid'])
#     print(i['imglist'])

# 插入数据
# mymongo.insert({'datetime':tzinfo.localize(datetime.datetime.now()),'code':4561,'email':'123456@qq.com'})

# 查询数据
# res = mymongo.find_one({'email':'123456@qq.com'})
# print(res['code'])
# print(type(res))


# 序列器(单个序列化)
def myser(model, many=False):
    # 判断
    if many == False:

        # 第一次转换
        mymodel = model_to_dict(model)

        return mymodel
    # 多个
    else:
        # 多个转换

        return list(model.dicts())


# 创建数据库连接对象
# 数据库连接池
database = peewee_async.PooledMySQLDatabase("mytornado", host='127.0.0.1', port=3306, user='root', password='.')


#  测试表
# 用户表
class Test_User(peewee.Model):
    username = peewee.CharField(null=False, default=None)
    password = peewee.CharField(null=False, default=None)

    class Meta:
        database = database


# 评论表
class Test_Comment(peewee.Model):
    uid = peewee.IntegerField(null=True, default=0)
    pid = peewee.IntegerField(null=True, default=0)
    comment = peewee.CharField(null=True, default=True)
    create_date = peewee.DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = database


# 产品表
class Test_Products(peewee.Model):
    name = peewee.CharField(null=True, default=True)
    img = peewee.CharField(null=True, default=True)
    price = peewee.IntegerField(null=True, default=0)
    # 评论数
    comment = peewee.IntegerField(null=True, default=0)

    class Meta:
        database = database


# 订单详情
class Test_Orders(peewee.Model):
    pid = peewee.IntegerField(null=True, default=0)
    uid = peewee.IntegerField(null=True, default=0)
    price = peewee.IntegerField(null=True, default=0)
    num = peewee.IntegerField(null=True, default=0)
    # 订单号
    number = peewee.IntegerField(null=True, default=0)
    create_date = peewee.DateTimeField(default=datetime.datetime.now)

    class Meta:
        database = database


# Test_User.create_table(True)
# Test_Comment.create_table(True)
# Test_Products.create_table(True)
# Test_Orders.create_table(True)

# 评论表
class Comment(peewee.Model):
    # 帖子id
    sid = peewee.IntegerField(null=False, default=None)
    # 评论人id
    uid = peewee.IntegerField(null=False, default=None)
    # 回复人id   0
    touid = peewee.IntegerField(null=False, default=None)
    # 评论
    content = peewee.CharField(null=False, default=None)

    class Meta:
        database = database


# Comment.create_table(True)


# 关系表
class Sub_Talk(peewee.Model):
    # 帖子id
    sid = peewee.IntegerField(null=False, default=None)
    # 话题表id
    tid = peewee.IntegerField(null=False, default=None)

    class Meta:
        database = database


# 话题表
class Talk(peewee.Model):
    title = peewee.CharField(null=False, default=None)
    desc = peewee.CharField(null=False, default=None)

    class Meta:
        database = database


# 帖子表
class Subject(peewee.Model):
    # 帖子内容
    info = peewee.CharField(null=False, default=None)
    # 用户id
    uid = peewee.IntegerField(null=False, default=None)
    # 发表时间
    create_date = peewee.DateTimeField(default=datetime.datetime.now)
    # 帖子种类  [0公开    1粉丝      2好友      3仅自己可见]
    type = peewee.IntegerField(null=False, default=None)
    # 收藏次数
    collect = peewee.IntegerField(null=False, default=None)
    # 帖子图片
    img = peewee.CharField(null=False, default=None)
    # 帖子视频
    video = peewee.CharField(null=False, default=None)
    # 评论
    comment = peewee.IntegerField(null=False, default=None)
    # 点赞
    agree = peewee.IntegerField(null=False, default=None)
    # 阅读次数
    read = peewee.IntegerField(null=False, default=None)

    class Meta:
        database = database


# 设置数据库类
# 用户表
class User(peewee.Model):
    # 字段
    username = peewee.CharField(null=False, default=None)
    password = peewee.CharField(null=False, default=None)
    phone = peewee.CharField(null=False, default=None)
    email = peewee.CharField(null=False, default=None)
    age = peewee.IntegerField(null=False, default=None)
    # //粉丝
    num = peewee.IntegerField(null=False, default=None)
    # //关注
    flow = peewee.IntegerField(null=False, default=None)
    reg = peewee.DateTimeField(default=datetime.datetime.now)
    # 状态,默认0(未注册)  1(注册)
    state = peewee.IntegerField(default=0)
    img = peewee.CharField(default=None, null=False)
    ding = peewee.CharField(default=None, null=False)

    class Meta:
        database = database


class K_User(peewee.Model):
    username = peewee.CharField(default=None, null=False)
    password = peewee.CharField(default=None, null=False)
    user_level = peewee.IntegerField(default=None, null=False)

    class Meta:
        database = database


class K_Shop(peewee.Model):
    title = peewee.CharField(default=None, null=False)
    price = peewee.IntegerField(default=None, null=False)
    num = peewee.IntegerField(default=0, null=False)

    class Meta:
        database = database


class K_You(peewee.Model):
    price = peewee.IntegerField(default=None, null=False)

    class Meta:
        database = database


class K_Cate(peewee.Model):
    uid = peewee.IntegerField(default=None, null=False)
    price = peewee.IntegerField(default=None, null=False)
    num = peewee.IntegerField(default=None, null=False)
    sid = peewee.IntegerField(default=None, null=False)
    sum = peewee.IntegerField(default=None, null=False)

    class Meta:
        database = database


# K_User.create_table(True)
# K_Cate.create_table(True)
# K_You.create_table(True)
# K_Shop.create_table(True)

# 登录查询sql查询
# select * from `user` where username = '' and password = ''

# orm查询  get找不到就会报错
# 单对象
# user = User.select().where ((User.username == '9905') & (User.password == '2')).get()
# print(type(user))
# print(user)
# print(myser(user))
# res = myser(user)
# print(res['username'])

# 多对象
# users = User.select()
# print(type(users))
# print(users)

# res = myser(users,many=True)
# print(res)


# for i in users:
# print(i.username)
# print(myser(users))
# res = myser(users)
# print(res['username'])

# 创建表
# Sub_Talk.create_table(True)
# Subject.create_table(True)
# Talk.create_table(True)


# 删除
# User.drop_table(True)
# exit(-1)

# 添加数据
# res = User.create(username='测试账号',age=20,phone='1234567890')
# print(res)

# 查询
# res = User.get(id=1)


# # 修改
# res.username = '修改账号'
# res.save()

# print(res)

# # 删除         双等   类中的信息     执行
# User.delete().where(User.id == 2).execute()
